/**
 * 用户管理数据表
 * @version 1.0.0
 * @author yangyibao
 */
var userDataTable;
var isSubmit = false;
var curDepartStr = "";
var curDepartList ;
var curGroupStr = "";
var roleIdStr = "";
var GroupArray;
$(function() {
	$.ajax({
		url:"../system/groupVO/queryGroup",
		async:false,
		dataType:'json',
		success:function(data){
			GroupArray = data;
		}
	});
	
	$.post("../power/queryAllRole",function(data){
		roleIdStr="<option value=''></option>";
		console.log(data);
		for(var i=0;i<data.length;i++){
			roleIdStr+="<option value='"+data[i].roleId+"'>"+data[i].roleName+"</option>";
		}
	});
	
    //ajax动态获取所有的role
    $.post("../power/queryAllRole",function(data){for(var i = 0 ; i < data.length ; i++){$("#roles").append("<option value ='"+data[i].roleId+"'>"+data[i].roleName+"</option>");}});
    $.post("../system/sysDepartmentVO/querySysDepartmentVOPageList?iDisplayStart=0&iDisplayLength=100000000", function(data){
    	curDepartStr = "";
    	var newData = data.aaData;
    	curDepartList = newData;
    	for(var i = 0 ; i < newData.length ; i++){
    		var depart = newData[i];
    		var str = "<option value='"+ depart.departmentId+"'"+">"+depart.departmentName+"</option>";
    		curDepartStr = str +curDepartStr;
    	}
    });
    $("#thisGroupId").selectpicker('render');
	$("#thisGroupId").selectpicker('refresh');
    $.post("../system/groupVO/queryGroup",function(data){
    	var str = "";
    	for(var i = 0 ; i < data.length ; i++){
    		str += "<option value='"+data[i].groupId+"'>"+data[i].groupName+"</option>";
    	}
    	$('#thisGroupId').append(str);
    });
    
    //数据列表数据
    userDataTable = $('#userDataTable').DataTable({
    	   "bProcessing": true,
           "bLengthChange":true,
           "bFilter": false,
           "bServerSide": true,
           "iDisplayLength":10,//默认数据条数
           "bSort": true,
           "pagingType":"full_numbers",
    	   "sAjaxSource": "../user/queryUsers",
           "fnServerParams" : function(aDataSet) {
        	   						aDataSet.push(
        	   								{"name" : "userRole","value" :$("#roles").val()},
        	   								{"name" : "userNo","value":$("#userNo1").val()},
        	   								{"name" : "createStartDt","value":""},
        	   								{"name" : "createEndDt","value":""},
        	   								{"name" : "userExt3","value":$("#userSearchForm #userExt3").val()},
        	   								{"name" : "userExt2","value":$("#userSearchForm #userExt2").val()},
        	   								{"name" : "userName","value" : $("#userName").val()});},
           "fbServerData":function(sSource,aDataSet){$.ajax({"dataType":"json","type":"GET","url":sSource,"data":aDataSet});},
           "aoColumns":[{"mDataProp":"userNo"},{"mDataProp":"userName"},{"mDataProp":"ext1"},{"mDataProp":"extStr3"},
        	   {"mDataProp":"groupId"},
        	   {"mDataProp":"createDate"},{"mDataProp":"locked"}],	
           "aoColumnDefs": [
         		{ orderable:false,targets:[1,2,3,4,5]}, //指定的列,禁用排序
    			{"aTargets":[0],"mRender":function(data,type,full){return (full.locked)?data+"&nbsp;<span class='label label-danger'><i class='icon-lock'></i></span>":data;}},
    			{"aTargets": [6],"mRender":function (data, type, full) {
    				var operation="<div class='btn-group '><a class='btn btn-operate-left' href='#' data-toggle='dropdown'><i class='icon-user'></i> 用户详情</a><a href='#' type='button' class='btn btn-operate-right dropdown-goggle' data-toggle='dropdown' aria-haspopup='true' aria-expanded='false'><span class='caret'></span></a>"
    				operation+="<ul class='dropdown-menu'>";
    				operation+="<li><a id='query' class='mini' data-id='"+full.userId +"'data-json='"+JSON.stringify(full) +"'><i class='icon-search'></i> 用户详情</a></li>";
    				operation+="<li><a id='reset' class='mini' data-value='"+full.userNo+"' data-id='"+full.userId +"'><i class='icon-key'></i> 重置密码</a></li>";
    				operation+="<li><a id='alterRole' class='mini' data-value='"+full.userNo+"' data-id='"+full.userId +"'><i class='icon-user'></i> 变更角色</a></li>";
    				operation+="<li><a id='updateDepart' class='mini' data-depart='"+full.extStr3+"' user-id='"+full.userId +"'><i class='icon-user'></i> 变更组织</a></li>";
    				operation+="<li><a id='updateGroup' class='mini'  user-id='"+full.userId +"' group-id='"+full.groupId+"'><i class='icon-user'></i> 变更群组</a></li>";
    				operation+="<li><a id='dltRole' class='mini' data-name='"+full.userName+"' data-id='"+full.userId +"'><i class='icon-remove'></i> 删除用户</a></li>"
    				operation+="</ul></div>";
    				return operation;
                    }
                },
                {"aTargets": [1,2,3],"mRender":function (data, type, full) {if(data!=null&&data!="")return data;else return "<font color='font-red-mint'>尚未设置</font>";}},
                {"aTargets":[4],"mRender":function(data, type, full){
                	return getGroupName(data);
                }}],      				       
          "oLanguage":{"sUrl": "../resources/assets/plugins/dataTables/txt/page.txt"},
          "initComplete":function () {
            $('#userDataTable_length').find('select').selectpicker('render');
            $('#userDataTable_length').find('select').selectpicker('refresh');
            $('#userDataTable_length').find('.btn-group').css('width','auto');
            $('#userDataTable_length').find('.btn').css('background-color','#fff');
            $('#userDataTable_length').find('.btn').css('border','#d8d8d8 solid 1px')
          }
     });
    
    //变更群组
    $('#userDataTable tbody').on('click','#updateGroup',function(){
    	var userId = $(this).attr("user-id");
    	$('#userGroupMgrDiv #userId').val(userId);
    	var groupId = $(this).attr("group-id");
    	$("#thisGroupId").selectpicker('render');
    	$("#thisGroupId").selectpicker('refresh');
    	if(groupId!=null){
        	var strArr = groupId.split(",")
        	for(var i = 0;i < strArr.length;i++){
        		$("#thisGroupId").selectpicker('val',strArr);
        	}
    	}
    	
    	$('#userGroupMgrDiv').modal('show');
    });
    
    $('#userGroupSaveBtn').click(function(){
    	var groupIdStr = $('#thisGroupId').val();
    	$.post('../system/groupVO/saveGroupIdtoUser',{"userId":$('#userGroupMgrDiv #userId').val(),"groupIdStr":groupIdStr==null?'':groupIdStr.toString()},function(data){
			if(data){
				swal("成功!","操作成功", "success");
				userDataTable.ajax.reload();
				$('#userGroupMgrDiv').modal('hide');
			}else{
				swal("失败!","操作失败", "error");
			}
    	});
    });
    
	//锁定/解锁用户按钮点击事件属性
    $("#userDataTable tbody").on('click', '#dltRole',function() {
       	 var id = $(this).attr("data-id");
		 var name = $(this).attr("data-name");
//		 confirm("您确定要删除"+name+"用户吗 ?",function(isConfirm){if (isConfirm) {$.post("../user/deleteUser",{userId:id},function(data){if(data.flg){reloadUsers();succ();}else{error();}});}else {cancel();}});
		 confirm("您确定要删除"+name+"用户吗 ?",function(isConfirm){if (isConfirm) {$.post("../user/deleteUserUpdate",{userId:id},function(data){if(data.flg){reloadUsers();succ();}else{error();}});}else {cancel();}});
    });
       	    
    //用户详细信息查询按钮点击事件属性
    $("#userDataTable tbody").on('click', '#query',function() {
    	var json = $.parseJSON($(this).attr("data-json"));
      	 $("#userInfoDiv .modal-body").html(userInfoDiv(json));
		 $("#userInfoDiv").modal("show"); 
    });
    
    //变更组织信息
    $("#userDataTable tbody").on('click', '#updateDepart',function() {
    	var userId = $(this).attr("user-id");
    	var departName = $(this).attr("data-depart");
    	var curSeleted = "";
    	for(var i=0; i<curDepartList.length; i++ ){
    		var data = curDepartList[i];
    		if(data.departmentName == departName){
    			curSeleted = data.departmentId;
    		}
    	}
    	$("#userDepartForm #userId").val(userId);
    	$("#userDepartForm #departId").html(curDepartStr);
    	$("#userDepartForm #departId").selectpicker('render');
   		$("#userDepartForm #departId").selectpicker('refresh');
    	$("#userDepartForm #departId").selectpicker('val',curSeleted);
    	$("#userDepartMgrDiv").modal("show");
    });
    //保存按钮
     $("#userDepartSaveBtn").click(function(){
    	var puserId = $("#userDepartForm #userId").val();
     	var pdepartId = $("#userDepartForm #departId").val();
     	$.post("../user/updateUserDepart",{userId:puserId,departId:pdepartId},function(data){
     		if(data.flg) {swal("成功!","当前操作成功!", "success");reloadUsers();$("#userDepartMgrDiv").modal("hide");}
     		else swal("失败!",data.errorMsg, "error");
     	});
   	});
   	
    
    
    //重置用户密码按钮点击事件属性
    $("#userDataTable tbody").on('click', '#reset',function() {
       	var id = $(this).attr("data-id");
       	var name = $(this).attr("data-value");
       	confirm("您确定要重置["+name+"]密码?",function(isConfirm){if(isConfirm) {$.post("../user/resetUserPwd",{userId:id,userNo:name},function(data){if(data.flg) {swal("", "当前操作成功 :)", "success");reloadUsers();}else swal("失败", data.errorMsg, "error");});} else swal("取消", "您的操作已经取消 :)", "error");});
   	});
   	
    //用户变更角色按钮点击事件属性
   	$("#userDataTable tbody").on('click', '#alterRole',function() {roleInfoDiv($(this).attr("data-id"),$('#roles').val());});
   	
   	//变更角色按钮点击属性
   	$("#alterRoleBtn").click(function(){
    	$.post("../user/updateUserRole",{userId:$('#userRoleId').val(),role:$('input:radio:checked').val()},function(data){
    		if(data.flg) {swal("成功!","用户角色变更成功!", "success");reloadUsers();}
    		else swal("失败!",data.errorMsg, "error");
    	});
	 });
   	
   	//新增用户按钮点击事件
   	$("#saveUser").click(function(){
   		$("#userSaveDiv .modal-body").html(userSaveDiv(curDepartStr,roleIdStr));
   		$("#userSaveDiv #departId").selectpicker('render');
   		$("#userSaveDiv #departId").selectpicker('refresh');
   		$("#userSaveDiv #roleDefaultId").selectpicker('render');
   		$("#userSaveDiv #roleDefaultId").selectpicker('refresh');
   		$("#userSaveDiv").modal("show");
   		//新增用户校验
   	   	$("#userBaseForm").validate({
   			  errorElement: 'span',
   			  errorClass:'help-inline',
   			  focusInvalid: false,ignore: '',
   			  rules: {userNo: {required: true,pattern:/^[a-z\d]{2,15}$/,remote:{type:'post',url:'../user/nameNoLockVaild',data: {userNo:function(){return $("#userNo").val();}},dataType: "json",dataFilter:function (data){return data;}}},
				      userName:{required: true,pattern:/^[\u4e00-\u9fa5]{2,10}$/},userTel:{required: true,mobileCN:true},userEmail:{required: true,email:true},departId:{required:true}},
   			  messages:{userNo:{pattern:'用户账号格式非法!',remote:'该账号已经存在！'},userName:{pattern:'用户名格式非法,必须是中文!'}},
   			  errorPlacement: function(error,element){error.insertAfter(element);},
    		  highlight: function(element) {
    			  $(element).closest('.control-group').removeClass('success');
    			  $(element).closest('.help-inline').removeClass('valid');
    			  $(element).closest('.help-inline').removeClass('ok');
    			  $(element).closest('.control-group').addClass('error');
    		  },
			  unhighlight: function(element) {$(element).closest('.control-group').removeClass('error');},
			  success: function(label) {
				  label.closest('.control-group').removeClass('error');
				  label.closest('.control-group').addClass('success');
				  label.closest('.help-inline').addClass('valid ok');
			  },
   			  submitHandler:function(form){
   				 if(!isSubmit){
   					isSubmit = true;
   					$.post("../user/addUserBase",$("#userBaseForm").serialize(),function(data){
      			    		if(data.flg) {
      			    			 swal("成功!","用户添加成功!", "success");
      			    			 $("#userSaveDiv").modal("hide");
      			    			reloadUsers();
      			    			isSubmit = false;
      			    	    } else swal("失败!",data.errorMsg, "error");
      			    });
//   					submitHandler:function(form){
//   					 if(!isSubmit){
//   						isSubmit = true;
//   						var postData = $("#userBaseForm").serialize();
//   						/**
//   						 * 自定义属性
//   						 * 1.将拓展属性拼接成json字符串
//   						 * 2.json转字符串
//   						 * 3.重新拼接请求参数
//   						 */
//   						//1.构建自定义json,取值应从对应的控件取值
//   						var extJson = {};
//   						extJson.com="com1";
//   						extJson.time="2018";
//   						extJson.other="extOther";
//   						//2.json转字符串
//   						var extJsonStr = "userExtJson=" + JSON.stringify(extJson);
//   						//3.重新拼接请求参数
//   						postData = postData+"&"+extJsonStr;
//   						//4.调用新增方法
//   						$.post("../user/addUserBase",postData,function(data){
//   							if(data.flg) {
//   								swal("成功!","用户添加成功!", "success");
//   								$("#userSaveDiv").modal("hide");
//   								reloadUsers();
//   								isSubmit = false;
//   							} else swal("失败!",data.errorMsg, "error");
//   						});
//   						
//   						//字符串 转json(修改时使用)
//   						//$.parseJSON(user.userExtJson);
//   					  }
//   					 }
//   					3.修改自定义属性接口
//   						/**
//   						 * 自定义属性
//   						 * 1.将拓展属性拼接成json字符串
//   						 * 2.json转字符串
//   						 * 3.重新拼接请求参数
//   						 */
//   						//1.构建自定义json,取值应从对应的控件取值
//   						var extJson1 = {};
//   					   	extJson1.com="com2";
//   						extJson1.time="2020";
//   					    extJson1.other="extOther2";
//   						//2.json转字符串并拼接请求参数
//   						var extJson1Str = "userExtJson=" + JSON.stringify(extJson1);
//   						3.重新拼接请求参数
//   						var url = "userId=530&"+extJson1Str;
//   						//4.调用修改方法
//   						$.post("../user/updateUser",postData,function(data){
//   							if(data.flg) {
//   								swal("成功!","用户修改成功!", "success");
//   								$("#userSaveDiv").modal("hide");
//   								reloadUsers();
//   								isSubmit = false;
//   							} else swal("失败!",data.errorMsg, "error");
//   						});
//   					  4.删除将userExtJson=""即可，如果不传那么不会产生变化
   				 }
   			      return false;
   			  }});
   	  });
   	
   	//新增用户信息
   	$("#userAddBtn").click(function(){
   		$("#userBaseForm").submit();
   	});
   	
});

function getGroupName(data){
	var str = "";
	if(data==null||data==undefined){
		data="";
	}
	var arr = data.split(",");
	for(var i=0;i<arr.length;i++){
		for(var j=0;j<GroupArray.length;j++){
			if(arr[i]==GroupArray[j].groupId){
				if(i==arr.length-1){
					str+=GroupArray[j].groupName;
				}else{
					str+=GroupArray[j].groupName+",";
				}
			}
		}
	}
	return str;
}

//数据表刷新
function reloadUsers(){
	userDataTable.ajax.reload();
}
